package jxau.jwgl.service.impl;

import jxau.jwgl.api.EvaluationApi;
import jxau.jwgl.api.JWGLServerException;
import jxau.jwgl.api.MessageData;
import jxau.jwgl.api.WebApiFactory;
import jxau.jwgl.commons.entity.Evaluation;
import jxau.jwgl.commons.entity.EvaluationTeach;
import jxau.jwgl.service.EvaluationService;
import jxau.jwgl.service.EvaluationTask;
import jxau.jwgl.service.UserService;
import jxau.jwgl.task.TaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;

/**
 * EvaluationServiceImpl
 *
 * @author LongShu 2017/06/09
 */
@Service
public class EvaluationServiceImpl implements EvaluationService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private EvaluationApi evaluatingApi = WebApiFactory.get(EvaluationApi.class);

    @Autowired
    private UserService userService;
    @Autowired
    private TaskExecutor evaluationExecutor;

    @Override
    @Cacheable(cacheNames = "evaluation", key = "#username+'_'+#semester")
    public List<EvaluationTeach> evaluationList(String username, String semester) {
        String guid = userService.getGuid(username);
        try {
            Response<MessageData<EvaluationTeach>> response = evaluatingApi.evaluatingList(guid, semester).execute();
            MessageData<EvaluationTeach> messageData = response.body();
            return messageData.getData();
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
            throw new JWGLServerException("教务系统错误,获取评教列表失败!");
        }
    }

    @Override
    @CacheEvict(cacheNames = "evaluation", key = "#username+'_'+#evaluation.semester")
    public int submitEvaluation(String username, Evaluation evaluation) {
        String guid = userService.getGuid(username);
        evaluation.setUsername(username);// 后台任务ID的一部分
        // 添加到后台任务
        EvaluationTask evaluationTask = new EvaluationTask(guid, evaluation);
        evaluationExecutor.addTask(evaluationTask);
        // 返回评教数量
        return evaluationTask.getCount();
    }

    @Override
    @CacheEvict(cacheNames = "evaluation", key = "#username+'_'+#semester", condition = "#result==true")
    public boolean isEvaluating(String username, String semester) {
        String id = "Evaluation" + username + semester;
        return !evaluationExecutor.isFinish(id);
    }

}
